﻿using System;
using System.Collections.Generic;
using System.Linq;
using Activity.Data;
using Activity.Model;
using Newtonsoft.Json;

namespace Activity.API
{
    public class TaskSetHandler
    {
        public IList<VShopModel.CoreModel> GetShopList(string BigAreaName, string AreaName, string ShopStr)
        {
            try
            {
                var dbRPT = new ActivityEntities();
                var list = dbRPT.V_ShopList.Where(
                    d => (d.ShopStateID == "00000000000011" || d.ShopStateID == "00000000000017") &&
                         ((string.IsNullOrEmpty(BigAreaName) || d.BigAreaName == BigAreaName) &&
                          (string.IsNullOrEmpty(AreaName) || d.AreaName == AreaName)) &&
                          (string.IsNullOrEmpty(ShopStr) || d.shopname.Contains(ShopStr))).Select(
                    d => new VShopModel.CoreModel
                    {
                        ShopID = d.shopid,
                        ShopCode = d.shopcode,
                        ShopName = d.shopname,
                        AreaName = d.AreaName,
                        BigAreaName = d.BigAreaName,
                        CompanyID = d.CompanyID,
                    }).OrderBy(d => d.BigAreaName).ThenBy(d => d.AreaName).ThenBy(d => d.ShopID).ToList();
                return list;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public IList<AreaModel.ListModel> GetAreaList()
        {
            try
            {
                var db = new HKERPEntities();
                var list = db.Bas_Area.ToList();
                var newList = list.Where(d => d.Level == 1).Select(d => new AreaModel.ListModel
                {
                    AreaID = d.AreaID,
                    AreaName = d.AreaName,
                    child = list.Where(r => r.Level == 2 && r.ParentID == d.AreaID).Select(r => new AreaModel.CoreModel
                    {
                        AreaID = r.AreaID,
                        AreaName = r.AreaName,
                    }).ToList(),
                }).ToList();
                return newList;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public int CreateTask(string UserIDStr, string TaskName, string TaskTypeStr, string ExecWeekStr, string ImgCountStr, string IsEnabledStr, string IsMustFinishStr,
            string TaskDescribe, string ShopListStr)
        {
            var db = new ActivityEntities();
            using (var tran = db.Database.BeginTransaction())
            {
                try
                {
                    var UserID = Convert.ToInt32(UserIDStr);
                    var TaskType = Convert.ToInt32(TaskTypeStr);
                    var ExecWeek = Convert.ToInt32(ExecWeekStr);
                    var ImgCount = Convert.ToInt32(ImgCountStr);
                    var isEnabled = Convert.ToBoolean(IsEnabledStr);
                    var isMustFinish = Convert.ToBoolean(IsMustFinishStr);
                    var ShopList = JsonConvert.DeserializeObject<IList<string>>(ShopListStr);

                    if (db.t_task_set.Any(d => d.TaskType == TaskType))
                    {
                        return 0;
                    }
                    else
                    {
                        var query = new t_task_set
                        {
                            TaskName = TaskName,
                            TaskType = TaskType,
                            ExecWeek = ExecWeek,
                            ImgCount = ImgCount,
                            TaskDescribe = TaskDescribe,
                            CreateDate = DateTime.Now,
                            IsEnabled = isEnabled,
                            IsMustFinish = isMustFinish,
                            Creator = UserID,
                        };
                        db.t_task_set.Add(query);
                        db.SaveChanges();
                        SaveShopTask(db, query.TaskID, ShopList);
                        db.SaveChanges();
                        tran.Commit();
                        return 1;
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Log.Error(ex);
                    return -1;
                }
            }
        }

        public int UpdateTask(string UserIDStr, string TaskIDStr, string TaskName, string TaskTypeStr, string ExecWeekStr, string ImgCountStr, string IsEnabledStr, string IsMustFinishStr,
            string TaskDescribe, string ShopListStr)
        {
            try
            {
                var UserID = Convert.ToInt32(UserIDStr);
                var TaskID = Convert.ToInt32(TaskIDStr);
                var TaskType = Convert.ToInt32(TaskTypeStr);
                var ExecWeek = Convert.ToInt32(ExecWeekStr);
                var ImgCount = Convert.ToInt32(ImgCountStr);
                var isEnabled = Convert.ToBoolean(IsEnabledStr);
                var isMustFinish = Convert.ToBoolean(IsMustFinishStr);
                var ShopList = JsonConvert.DeserializeObject<IList<string>>(ShopListStr);
                var db = new ActivityEntities();
                if (db.t_task_set.Any(d => d.TaskType == TaskType && d.TaskID != TaskID))
                {
                    return 0;
                }
                else
                {
                    var query = db.t_task_set.FirstOrDefault(d => d.TaskID == TaskID);
                    if (query != null)
                    {
                        query.TaskName = TaskName;
                        query.TaskType = TaskType;
                        query.ExecWeek = ExecWeek;
                        query.ImgCount = ImgCount;
                        query.TaskDescribe = TaskDescribe;
                        query.CreateDate = DateTime.Now;
                        query.IsEnabled = isEnabled;
                        query.IsMustFinish = isMustFinish;
                        query.Creator = UserID;
                    }
                    SaveShopTask(db, TaskID, ShopList);
                    db.SaveChanges();
                    return 1;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return -1;
            }
        }

        public void SaveShopTask(ActivityEntities db, int TaskID, IList<string> ShopList)
        {
            try
            {
                var sql = $@"DELETE FROM dbo.t_task_shoplist WHERE TaskID='{TaskID}'";
                db.Database.ExecuteSqlCommand(sql);
                if (ShopList != null)
                {
                    foreach (var shopID in ShopList)
                    {
                        var taskShop = new t_task_shoplist
                        {
                            TaskID = TaskID,
                            ShopID = shopID,
                        };
                        db.t_task_shoplist.Add(taskShop);
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public TaskSetModel.NeceModel GetTask(string TaskIDStr)
        {
            try
            {
                var TaskID = Convert.ToInt32(TaskIDStr);
                var db = new ActivityEntities();
                var query = db.t_task_set.FirstOrDefault(d => d.TaskID == TaskID);
                var result = new TaskSetModel.NeceModel
                {
                    TaskID = query.TaskID,
                    TaskName = query.TaskName,
                    TaskType = query.TaskType,
                    ExecWeek = query.ExecWeek,
                    ImgCount = query.ImgCount,
                    IsEnabled = query.IsEnabled,
                    IsMustFinish = query.IsMustFinish,
                    TaskDescribe = query.TaskDescribe,
                    shopList = (from vShop in db.V_ShopList
                                join tShop in db.t_task_shoplist on vShop.shopid equals tShop.ShopID
                                where tShop.TaskID == TaskID
                                select new VShopModel.CoreModel
                                {
                                    ShopID = vShop.shopid,
                                    ShopCode = vShop.shopcode,
                                    CompanyID = vShop.CompanyID,
                                    AreaName = vShop.AreaName,
                                    BigAreaName = vShop.BigAreaName,
                                    ShopName = vShop.shopname,
                                }).ToList(),
                };
                return result;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

        public int DeleteTask(string TaskIDStr)
        {
            try
            {
                var TaskID = Convert.ToInt32(TaskIDStr);
                var sql = $@"UPDATE dbo.t_task_set SET IsRemove = 1 WHERE TaskID='{TaskID}'";
                var db = new ActivityEntities();
                SaveShopTask(db, TaskID, null);
                db.Database.ExecuteSqlCommand(sql);
                db.SaveChanges();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return -1;
            }
        }

        public IList<TaskSetModel.CoreModel> GetTaskList()
        {
            try
            {
                var db = new ActivityEntities();
                var list = db.t_task_set.Where(d => d.IsRemove == false).Select(d => new TaskSetModel.CoreModel
                {
                    TaskID = d.TaskID,
                    TaskName = d.TaskName,
                }).ToList();
                return list;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return null;
            }
        }

    }
}
